package com.gbiac.modules.monitor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gbiac.modules.monitor.api.IMonitorApi;
import com.gbiac.modules.monitor.entity.*;
import com.gbiac.modules.monitor.param.UserCheckParam;
import com.gbiac.modules.monitor.param.UserSeatParam;
import com.gbiac.modules.monitor.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MonitorApiImpl implements IMonitorApi {

    @Resource
    private IUserSeatService userSeatService;

    @Resource
    private ISeatService seatService;
    @Resource
    private ISeatUserService seatUserService;
    @Resource
    private IUserCheckInService userCheckInService;
    @Resource
    @Lazy
    private ISysBaseAPI sysBaseAPI;

    @Resource
    private IRuleService ruleService;

    @Resource
    private ISeatFaceLoginService seatFaceLoginService;

    @Resource
    private IPalmVeinRecordService palmVeinRecordService;
    @Resource
    private AiDeviceService aiDeviceService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkIn(UserCheckParam param) {
        LoginUser user = sysBaseAPI.getUserByName(param.getUsername());

        Seat seat = seatService.getOne(new LambdaQueryWrapper<Seat>().eq(Seat::getIp, param.getClientIp()));
        if (seat == null) {
            throw new JeecgBootException("找不到席位信息");
        }
        if ("1".equals(seat.getDisable())) {
            throw new JeecgBootException("该席位已被禁用");
        }
        // 校验当前用户是否可以登录当前席位
        List<UserSeat> userSeatList = userSeatService.list(new LambdaQueryWrapper<UserSeat>().eq(UserSeat::getUserId, user.getId()).eq(UserSeat::getSeatId, seat.getId()));
        if (CollectionUtils.isEmpty(userSeatList)) {
            // 不允许登录当前席位
            throw new JeecgBootException("不允许登录此席位");
        }
        // 是否可以直接登录
        List<UserSeat> directlyUserSeatList = userSeatList.stream().filter((item) -> UserSeat.LoginType.DIRECTLY.equals(item.getLoginType())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(directlyUserSeatList)) {
            // 见习席登录
            // 判断当前部门所有席位上是否已有教员登录
            List<Seat> seatList = seatService.list(new LambdaQueryWrapper<Seat>().eq(Seat::getOrgCode, seat.getOrgCode()));
            List<SeatUser> seatUserList = seatUserService.list(new LambdaQueryWrapper<SeatUser>().in(SeatUser::getSeatId, seatList.stream().map(Seat::getId).collect(Collectors.toList())));
            boolean hasTeacher = false;
            for (SeatUser seatUser : seatUserList) {
                LoginUser u = sysBaseAPI.getUserById(seatUser.getUserId());
                if ("teacher".equals(u.getUserType())) {
                    hasTeacher = true;
                    break;
                }
            }
            if (!hasTeacher) {
                // 没有教员在线不允许登录当前席位
                throw new JeecgBootException("没有教员在线不允许登录此席位");
            }
        }
        // 当前席位是否有人已经在登录，如果是，则需要将当前席位的人员先离岗
        SeatUser seatUser = seatUserService.getOne(new LambdaQueryWrapper<SeatUser>().in(SeatUser::getSeatId, seat.getId()));
        if (seatUser != null && StringUtils.isNotBlank(seatUser.getUserId())) {
            // 将当前席位人员离岗
            userCheckInService.checkOut(seatUser.getUserId(), seatUser.getSeatId());
        }

        userCheckInService.checkIn(user.getId(), seat.getId());
    }

    @Override
    public void checkInTemp(UserCheckParam param) {
        LoginUser user = sysBaseAPI.getUserByName(param.getUsername());

        Seat seat = seatService.getOne(new LambdaQueryWrapper<Seat>().eq(Seat::getIp, param.getClientIp()));
        if (seat == null) {
            throw new JeecgBootException("找不到席位信息");
        }
        if ("1".equals(seat.getDisable())) {
            throw new JeecgBootException("该席位已被仅禁用");
        }
        // 判断当前用户是否已经在席位上
        long count = seatUserService.count(new LambdaQueryWrapper<SeatUser>().eq(SeatUser::getSeatId, seat.getId()).eq(SeatUser::getUserId, user.getId()));
        if (count == 0) {
            throw new JeecgBootException("回岗打卡失败，当前员工未在此席位上岗");
        }
        userCheckInService.checkInTemp(user.getId(), seat.getId());
    }

    @Override
    public void checkOut(UserCheckParam param) {
        LoginUser user = sysBaseAPI.getUserByName(param.getUsername());
        Seat seat = seatService.getOne(new LambdaQueryWrapper<Seat>().eq(Seat::getIp, param.getClientIp()));
        userCheckInService.checkOut(user.getId(), seat.getId());
    }

    @Override
    public void checkOutTemp(UserCheckParam param) {
        LoginUser user = sysBaseAPI.getUserByName(param.getUsername());
        Seat seat = seatService.getOne(new LambdaQueryWrapper<Seat>().eq(Seat::getIp, param.getClientIp()));
        userCheckInService.checkOutTemp(user.getId(), seat.getId());
    }

    @Override
    public void saveUserSeat(UserSeatParam userSeatParam) {
        userSeatService.saveUserSeat(userSeatParam);
    }

    @Override
    public String getUserSeatIds(String userId, String loginType) {
        List<UserSeat> UserSeatList = userSeatService.list(new LambdaQueryWrapper<UserSeat>().eq(UserSeat::getUserId, userId).eq(UserSeat::getLoginType, loginType));
        return UserSeatList.stream().map(UserSeat::getSeatId).collect(Collectors.joining(","));
    }

    @Override
    public Seat getSeatByUserId(String userId) {
        SeatUser seatUser = seatUserService.getOne(new LambdaQueryWrapper<SeatUser>().eq(SeatUser::getUserId, userId));
        if (seatUser == null) {
            return null;
        }
        Seat seat = seatService.getById(seatUser.getSeatId());
        return seat;
    }

    @Override
    public List<Rule> listLastRule() {
        return ruleService.listLastRule(new LambdaQueryWrapper<>());
    }

    @Override
    public void startFaceLogin(String clientIp) {
        Seat seat = seatService.getOne(new LambdaQueryWrapper<Seat>().eq(Seat::getIp, clientIp));
        if (seat == null) {
            throw new JeecgBootException("找不到席位信息");
        }
        if ("1".equals(seat.getDisable())) {
            throw new JeecgBootException("席位被禁用");
        }
        seatFaceLoginService.startLogin(seat.getId());
    }

    @Override
    public SeatFaceLogin getFaceLoginResult(String clientIp) {
        Seat seat = seatService.getOne(new LambdaQueryWrapper<Seat>().eq(Seat::getIp, clientIp));
        if (seat == null) {
            throw new JeecgBootException("找不到席位信息");
        }
        return seatFaceLoginService.getLoginResult(seat.getId());
    }

    @Override
    public Result<String> addPersonPalmVeinDevice(Boolean isLogin, LoginUser user) {
        return palmVeinRecordService.addPersonPalmVeinDevice(isLogin, user);
    }

    @Override
    public Result<String> batchAddPersonPalmVeinDevice(List<LoginUser> userList) {
        return palmVeinRecordService.batchAddPersonPalmVeinDevice(userList);
    }

    @Override
    public Result<String> addPersonAIDevice(LoginUser loginUser) {
        return aiDeviceService.addPersonAIDevice(loginUser);
    }

    @Override
    public Result<String> deletePersonAIDevice(String id) {
        return aiDeviceService.deletePersonAIDevice(id);
    }

    @Override
    public Result<String> batchAddPersonAIDevice(List<LoginUser> loginUserList) {
        return aiDeviceService.batchAddPersonAIDevice(loginUserList);
    }

    @Override
    public Result<String> deletePersonPalmVeinDevice(String id) {
        return palmVeinRecordService.deletePersonPalmVeinDevice(id);
    }
}
